#!/bin/sh

# program daemon shell script, it will keep the program on running.
#. /etc/profile
. ./PISPlayer_common

echo "-------running env:--------"
export 
echo "---------------------------"

cd $PROGRAM_BASE_DIR

while [ -f $RUN_FLAG ] ; do
	# check update
	if [ -f $UPDATE_FLAG ]; then	
		# check update
		if [ -f $PROGRAM_UPDATE_PATH ]; then
			set -x
			echo echo "[$SRV_NAME] update mode"
			# yes there is a update
			killall $PROGRAM_NAME
			
			dd if=/dev/zero of=/dev/fb0 bs=1024 count=4M 2>/dev/null
			
			mv $PROGRAM_PATH $PROGRAM_UPDATE_BACKUP_PATH
			mv $PROGRAM_UPDATE_PATH $PROGRAM_PATH
			chmod 755 $PROGRAM_PATH
			rm $UPDATE_FLAG
			touch $UPDATE_FAILED_FLAG
			set +x
		fi
	fi

	# check restart
	if [ -f $RESTART_FLAG ]; then	
		killall $PROGRAM_NAME
		rm $RESTART_FLAG
	fi
	
	#check program running status
	PRO_NOW=`ps c -ef | grep " $PROGRAM_NAME$" | grep -v "grep" | wc -l`

	if [ $PRO_NOW -eq 0 ]; then
		$PROGRAM_PATH &
		sleep 2
	fi

	#check program hang status
	PRO_STAT=`ps c -ef | grep " $PROGRAM_NAME$" |grep T|grep -v "grep"|wc -l`
	if [ $PRO_STAT -gt 0 ] ; then
		killall $PROGRAM_NAME
		sleep 2
		$PROGRAM_PATH &
		sleep 2
	fi

	sleep 2
done

exit 0
